// 页面加载完成后获取维修申请列表
document.addEventListener('DOMContentLoaded', () => {
    fetchRepairRequests();
});

// 获取维修申请列表
async function fetchRepairRequests() {
    try {
        const status = document.getElementById('statusFilter').value;
        const roomNo = document.getElementById('roomFilter').value;
        
        let url = '/api/repairs';
        const params = new URLSearchParams();
        if (status) params.append('status', status);
        if (roomNo) params.append('room_no', roomNo);
        if (params.toString()) url += '?' + params.toString();

        const response = await fetch(url);
        const requests = await response.json();
        displayRepairRequests(requests);
    } catch (error) {
        console.error('获取维修申请列表失败:', error);
        alert('获取维修申请列表失败');
    }
}

// 显示维修申请列表
function displayRepairRequests(requests) {
    const tbody = document.getElementById('repairList');
    tbody.innerHTML = '';

    requests.forEach(request => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${request.room_no}</td>
            <td>${request.student_name} (${request.student_id})</td>
            <td>${request.type}</td>
            <td>${request.description.length > 30 ? request.description.substring(0, 30) + '...' : request.description}</td>
            <td>
                <span class="status-badge ${getStatusClass(request.status)}">
                    ${request.status}
                </span>
            </td>
            <td>${new Date(request.created_at).toLocaleString()}</td>
            <td>
                <button class="action-btn" onclick="viewDetails(${request.id})">详情</button>
                ${request.status === '待处理' ? 
                    `<button class="action-btn process-btn" onclick="showProcessForm(${request.id})">处理</button>` : 
                    request.status === '处理中' ? 
                    `<button class="action-btn process-btn" onclick="showProcessForm(${request.id})">更新</button>` : 
                    (request.status === '已完成' || request.status === '已驳回') ?
                    `<button class="action-btn delete-btn" onclick="deleteRequest(${request.id})">删除</button>` : ''
                }
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 获取状态对应的CSS类
function getStatusClass(status) {
    switch (status) {
        case '待处理':
            return 'status-pending';
        case '处理中':
            return 'status-processing';
        case '已完成':
            return 'status-completed';
        case '已驳回':
            return 'status-rejected';
        default:
            return '';
    }
}

// 显示添加表单
function showAddForm() {
    document.getElementById('formTitle').textContent = '提交维修申请';
    document.getElementById('addEditForm').reset();
    document.getElementById('repairForm').style.display = 'block';
}

// 隐藏添加表单
function hideForm() {
    document.getElementById('repairForm').style.display = 'none';
    document.getElementById('addEditForm').reset();
}

// 显示处理表单
function showProcessForm(id) {
    document.getElementById('processRequestId').value = id;
    document.getElementById('processRepairForm').reset();
    document.getElementById('processForm').style.display = 'block';
}

// 隐藏处理表单
function hideProcessForm() {
    document.getElementById('processForm').style.display = 'none';
    document.getElementById('processRepairForm').reset();
}

// 查看维修申请详情
async function viewDetails(id) {
    try {
        const response = await fetch(`/api/repairs/${id}`);
        const request = await response.json();
        
        const detailsDiv = document.getElementById('repairDetails');
        detailsDiv.innerHTML = `
            <div class="details-content">
                <p><strong>宿舍号：</strong>${request.room_no}</p>
                <p><strong>申请人：</strong>${request.student_name} (${request.student_id})</p>
                <p><strong>维修类型：</strong>${request.type}</p>
                <p><strong>问题描述：</strong>${request.description}</p>
                <p><strong>申请状态：</strong>
                    <span class="status-badge ${getStatusClass(request.status)}">${request.status}</span>
                </p>
                <p><strong>申请时间：</strong>${new Date(request.created_at).toLocaleString()}</p>
                ${request.processed_at ? 
                    `<p><strong>处理时间：</strong>${new Date(request.processed_at).toLocaleString()}</p>` : ''}
                ${request.comment ? 
                    `<p><strong>处理意见：</strong>${request.comment}</p>` : ''}
            </div>
        `;
        
        document.getElementById('detailsModal').style.display = 'block';
    } catch (error) {
        console.error('获取维修申请详情失败:', error);
        alert('获取维修申请详情失败');
    }
}

// 隐藏详情模态框
function hideDetails() {
    document.getElementById('detailsModal').style.display = 'none';
}

// 处理维修申请表单提交
async function handleProcessSubmit(event) {
    event.preventDefault();

    const id = document.getElementById('processRequestId').value;
    const updateData = {
        status: document.getElementById('processStatus').value,
        comment: document.getElementById('processComment').value
    };

    try {
        const response = await fetch(`/api/repairs/${id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(updateData)
        });

        if (response.ok) {
            hideProcessForm();
            fetchRepairRequests(); // 刷新列表
            alert('处理成功');
        } else {
            const data = await response.json();
            throw new Error(data.error || '处理失败');
        }
    } catch (error) {
        console.error('处理维修申请失败:', error);
        alert(error.message || '处理维修申请失败');
    }
}

// 提交维修申请
async function handleSubmit(event) {
    event.preventDefault();

    const requestData = {
        room_no: document.getElementById('roomNo').value,
        student_id: document.getElementById('studentID').value,
        type: document.getElementById('type').value,
        description: document.getElementById('description').value
    };

    try {
        const response = await fetch('/api/repairs', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(requestData)
        });

        if (response.ok) {
            hideForm();
            fetchRepairRequests(); // 刷新列表
            alert('维修申请提交成功');
        } else {
            const data = await response.json();
            throw new Error(data.error || '提交失败');
        }
    } catch (error) {
        console.error('提交维修申请失败:', error);
        alert(error.message || '提交维修申请失败');
    }
}

// 删除维修申请
async function deleteRequest(id) {
    if (!confirm('确定要删除这条维修申请记录吗？')) {
        return;
    }

    try {
        const response = await fetch(`/api/repairs/${id}`, {
            method: 'DELETE'
        });

        if (response.ok) {
            fetchRepairRequests(); // 刷新列表
            alert('删除成功');
        } else {
            const data = await response.json();
            throw new Error(data.error || '删除失败');
        }
    } catch (error) {
        console.error('删除维修申请失败:', error);
        alert(error.message || '删除维修申请失败');
    }
}